import numpy as np

code = 0
msg = ""
cr = 0

def dealB(matrix,n):#由比较矩阵求得λ和ω
    # 列向量归一化
    sum = np.zeros(n)
    matrixx = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            sum[i] += matrix[j][i]
    for i in range(n):
        for j in range(n):
            matrixx[j][i] = matrix[j][i] / sum[i]
    # 求行和并归一化
    ω = np.zeros(n)
    for i in range(n):
        for j in range(n):
            ω[i] += matrixx[i][j]
    sumω = 0
    for i in range(n):
        sumω += ω[i]
    for i in range(n):
        ω[i] /= sumω
        ω[i] = round(ω[i],4)
    #求λ
    result = np.dot(matrix, ω)
    λ = 0
    for i in range(n):
        m = result[i] / ω[i]
        if m > λ:
            λ = m
    λ = round(λ,4)
    ω = ω.tolist()
    RItest1(λ,n)
    return ω,λ

#成对比较矩阵的一致性检验
def RItest1(λ,n):
    global code, msg, cr
    RI = [0, 0, 0.58, 0.90, 1.12, 1.24, 1.32, 1.41, 1.45, 1.49]
    CI = (λ-n)/(n-1)
    if n > 2:
        CR = CI/RI[n-1]
        if CR>=0.1:
            #print("该比较矩阵不能通过一致性检验，需要重新调整", end = "")  #最好改成弹窗提示
            code = 0
            msg = "该比较矩阵不能通过一致性检验，需要重新调整"
            cr = round(CR,4)
            #print({"code": 0,"ω": ω, "λ": λ, "CR": round(CR,4), "msg": "该比较矩阵不能通过一致性检验，需要重新调整"}, end = "")
        else:
            #print("通过一致性检验，CR=",round(CR,4), end = "")    #最好改成弹窗提示
            code = 1
            msg = "通过一致性检验，CR=" + str(round(CR,4))
            cr = round(CR,4)
            #print({"code": 1,"ω": ω, "λ": λ, "CR": round(CR,4), "msg": "通过一致性检验，CR=" + str(round(CR,4))}, end = "")
    else:
        #print("无需一致性检验", end = "")    #最好改成弹窗提示
        code = 1
        msg = "无需一致性检验"
        cr = round(CR,4)
        #print({"code": 0,"ω": ω, "λ": λ, "CR": round(CR,4), "msg": "无需一致性检验"}, end = "")


############# 验证算法
n = {{n}}   #n同样表示部件数量
matrix = {{matrix}}#[[1.0, 2.0, 3.0], [0.5, 1.0, 2.0], [0.3333, 0.5, 1.0]]
ω,λ = dealB(matrix,n)
#print({"ω": ω, "λ": λ}, end = "")
#print("ω=",ω)
#print("λ=",λ)
print({"code": code,"ω": ω, "λ": λ, "CR": round(cr,4), "msg": msg}, end = "")